package com.du.utils;

import com.du.constants.SsmConstans;
import com.du.vo.ResultVO;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 发送短信验证码工具类
 */
@Component
public class SendSMSUtil {
    @Value("${yunpian.apikey}")
    private static String apikey;

    /**
     * 发送短信工具类方法
     * @param phone
     *      手机号
     * @param session
     *      session对象
     * @return
     */
    public static ResultVO sendSms(String phone,HttpSession session){
        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient("005f9f49d154e8aca0312698729acd40").init();
        // 生成验证码
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        //将验证码放到Session域当中
        session.setAttribute(SsmConstans.USER_CODE,code);
        System.out.println(code);
        //发送短信API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, "15536825434");
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是"+code);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        System.out.println(r.getCode());
        System.out.println(r.getData());
        System.out.println(r.getMsg());
        System.out.println(r.getThrowable());
        System.out.println(r.getDetail());
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //返回结果对象
        ResultVO vo = new ResultVO(r.getCode(), r.getMsg(), null);
        //释放clnt
        clnt.close();
        //返回
        return vo;
    }

}
